unit Global;
{This Unit contains procedures, functions and declarations that are globaly used
in the application}

interface

uses
  Sharemem, SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, ExtCtrls, Menus, StdCtrls, Buttons, DB, wwtable, wwdatsrc, winsock,
  wwdblook, wwdbigrd, wwdbgrid, wwkeycb, dbCtrls, wwdbcomb, Wwdotdot, Mask, Grids, DBGrids,
  DBTables, Wwquery, wwdbedit, wwDBDlg, MDDBLookupCombo, wwdbdatetimepicker, fcColorCombo,
  wwClient, DBClient, MConnect, SConnect, Inifiles, ImgList, ImagePicker, DllStruct,
  dll96v1, ADOdb, BetterADODataset;

type
{$IFDEF WIN32}
  WParameter = LongInt;
{$ELSE}
  WParameter = Word;
{$ENDIF}
  LParameter = LongInt;

  TTreeObject = class(TObject)
    TreeKey: Integer;
    TreeString: string;
    TreeCaption: string;
    ShortCut: string;
  end;

(*   TSecurityVars = record
     ClientKey: Integer;
     ComputerName: String;
     SQLServerName: String;
     SQLDBName: String;
     SQLPassword: String;
     SQLUserName: String;
     ClientName: String;
     BDEAlias: String;
     bDCOMCon: Boolean;
     nStaffKey: Integer;
   end;
*)

  TCodeType = (ctnone, /// 0
    ctZip, /// 1
    ctDiagCategory, /// 2
    ctDiagnosis, /// 3
    ctApptType, /// 4
    ctadjustment, /// 5
    ctPayMethod, /// 6
    ctRefType, /// 7
    ctModify, /// 8
    ctSpeciality, /// 9
    ctLocation, /// 10
    ctReferral, /// 11
    ctCorporation, /// 12
    ctStaff, /// 13
    ctReason, /// 14
    ctPostcode, /// 15
    ctTreatment, /// 16
    ctPlaceOfService, /// 17
    ctTypeOfService, /// 18
    ctPosType, /// 19
    ctTOSType, /// 20
    ctClaimStatus, /// 21
    ctNarrative, /// 22
    ctResource, /// 23
    ctProcedureCategory, /// 24
    ctFees, /// 25
    ctBillType, /// 26
    ctMedication, /// 27
    ctCarrier, /// 28
    ctProvider, /// 29
    ctTask, /// 30
    ctContact, /// 31
    ctProcedure, /// 32
    ctDefaults, /// 33
    ctPlans, /// 34
    ctGuarantor, /// 35
    ctPolicyHolder, /// 36
    ctAttorney, /// 37
    ctPharmacy, /// 38
    ctEmployer, /// 39
    ctFacility, /// 40
    ctHospital, /// 41
    ctOffice, /// 42
    ctProblem, /// 43
    ctEmergency, /// 44
    ctLaboratory, /// 45
    ctBenefit, /// 46
    ctGLReference, /// 47
    ctDepartment, /// 48
    ctContract, /// 49
    ctGLCode, /// 50
    ctRejection, /// 51
    ctGuidelines, /// 52
    ctDRG, /// 53
    ctWriteOff, /// 54
    ctInstruction, /// 55
    ctBillingValidations, /// 56
    ctReferralReason, /// 57
    ctUBCondition, /// 58
    ctUBOccurrence, /// 59
    ctUBRevenue, /// 60
    ctUBValue, /// 61
    ctUBBillType, /// 62
    ctUserAction, /// 63
    ctTicklerType, /// 64
    ctDisclosure, /// 65
    ctReserved, /// 66
    ctAttachmentType, /// 67
    ctVendor, /// 68
    ctTypeGroup, /// 69
    ctBlocked, /// 70
    ctMedicationClass, /// 71
    ctPhraseType, /// 72
    ctImmunization, /// 73
    ctAllergy, /// 74
    ctFindingType, /// 75
    ctOrderType, /// 76
    ctCollectionType, /// 77
    ctMarProductstatus, /// 78
    ctchartreason, /// 79
    ctHospitalresource, /// 80
    ctAbbreviation, /// 81
    ctChartType, ///82
    ctEducation, ///83
    ctInsurancecontact, //84
    ctEdiDestination, //85
    ctMedicationRoute, //86
    ctMedicationDirection, //87
    ctMedicationStatus, //88
    ctMedicationForm, //89
    ctMedicationAction, //90
    ctHistoryStatus, //91
    ctEMRTreatment, //92
    ctTimer, //93
    ctAllergyReaction, //94
    ctDiscussions, //95
    ctProgress, //96
    ctMedicationSig, //97
    ctReminder, //98
    ctProgressType, //99
    ctOrderTypeTemplate, //100
    ctLabtest, //101
    ctCLManufacturer, //102
    ctCLBrand, //103
    ctCLType, //104
    ctLabForm, //105
    ctSmartextType, //106
    ctSystems, //107
    ctSymbolPhrases, //108
    ctPQRI, //109
    ctEducationType, //110
    ctCustomPlans, // 111 // ONC Changes by Abel, 01/07/2011
    ctProcedureType, //112
    ctAnesthesia, //113
    ctAntiseptic, //114
    ctPostProcedure, //115
    ctCLSolutions, //116
    ctCataractPlanNotes, //117
    ctSurgicalLens, //118
    ctSurgicalLensAxis, //119
    ctSurgicalLensPower, //120
    ctTicklerTemplate,//121
  	ctDiagnosis10,//122
    ctEncounterCodes,//123
    ctCCLPlanNotes, //124   //Added by: Gerald 1/15/2014
    ctCLPackaging, //125 //Added by: Gerald 8/19/2014
    ctSNOMED, //126
    ctLabPanel, //127
    ctOpticalCLShipping); //128
const
  Space = #$20;

function Capitalize(Texto:String): String;
function IsValidDate(MyTest: string): Boolean;
function AutoCapitalizeFirstLetter(Sender: TObject): string;
function GetVersionNumber(ModuleName: string): string;
function ShowScanlite(nIndex: Integer; LocationKey: Integer): Integer; overload;
function ShowScanlite(Caption, SourceType: string; SourceKey: Integer): Integer; overload;
function GetImageType(ImageStream: TMemoryStream): string;
function HasAccessRights(Staffkey, Right: Integer; ShowMessageBox: Boolean): Boolean;
function HasAccessRights_ADO(Staffkey, Right: Integer; ShowMessageBox: Boolean): Boolean;
function ConfirmCancel(MsgTXT: PChar; MsgTitle: string; Table: TObject; DataSource: TObject): Boolean;
function ConfirmCancel_ADO(MsgTXT: PChar; MsgTitle: string; Table: TObject; DataSource: TObject): Boolean;
function ConfirmCancel_BetterADO(MsgTXT: PChar; MsgTitle: string; Table: TObject; DataSource: TObject): Boolean;//Sarma

function ConfirmSave(MsgTXT: PChar; Table: TObject; DataSource: TObject): Boolean;
function ConfirmSave_ADO(MsgTXT: PChar; Table: TObject; DataSource: TObject): Boolean;
function CapFirst(MyString: string): string;
function CapAll(MyString: string): string;
function CapFirstLetter(S: string): string;
function StripName(Name: ShortString; var LastName, FirstName, MI: string): string;
function StripLastName(Name: ShortString): string;
function StripFirstName(Name: ShortString): string;
function StripMI(Name: ShortString): string;
function DisplayZoom(MyString: string): string;
function UpCaseFirstStr(S: string): string; //anil
function StripStr(S: string): string; //anil
procedure EnterField(Sender: TObject; Color: TColor);
procedure ExitField(Sender: TObject; Color: TColor);
procedure Function_Key_Press(Key: Word; Sender: TObject; Form: TForm;
//             Grid: TwwDBGrid; Table: TwwClientDataset);
  Grid: TwwDBGrid; ACol: LongInt; Table: TwwClientDataset);
procedure MoveTableColumn(Sender: TObject; FieldName: string; Order: integer);
procedure ChangeTableIndex(Sender: TObject; KCombo: TwwKeyCombo; Table: TwwClientDataset);
function ConfirmAndPost(LocalTable, MainTable: TwwClientDataset; sKey, mKey: string): Boolean;
function IsSameKey(wwMainTbl, wwTable: TwwClientDataset; short, keyname: string): Boolean;
function IsSameKey_ADO(wwMainTbl, wwTable: TADODataset; short, keyname: string): Boolean;
function IsShortValid(wwMainTbl, wwTable: TwwClientDataset; short, keyname: string): Boolean;
function IsShortValid_ADO(wwMainTbl, wwTable: TADODataset; short, keyname: string): Boolean;
function CapFirstMemoLetter(MyMemoList: TStrings): string;
procedure CodesRequiredMsg(CodeMsg: string); // CES Bordie
function CodesConfirmSaveMsg(ConfirmFormMsg: string): Integer;
function ConfirmToAddCode: Boolean;
function ConfirmToDelete: Boolean; // JOub
procedure DeleteItems(TableToDelete: TTable; ByField: TField);

function OpenPhraseFinderForm(PhraseFinderVars: TPhraseFinderVars; fADOConn: TADOConnection): LongInt;

function GetKeyValue(DCOMConnection: TDCOMConnection; TempQueryProvName: string; TableName: string; VField: string): Integer; overload;
function GetKeyValue_ADO(FADOConn: TADOConnection; TableName: string; VField: string): Integer;
function GetKeyValue(SocketConnection: TSocketConnection; TempQueryProvName: string; TableName: string; VField: string): Integer; overload;
function GetKey(DCOMConnection: TDCOMConnection; NumberTableProvName, TempQueryProvName: string; TableName, ItemName: string): LongInt; overload;
function GetKey(SocketConnection: TSocketConnection; NumberTableProvName, TempQueryProvName: string; TableName, ItemName: string): LongInt; overload;
function GetKey_ADO(FADOConn: TADOConnection; TableName, ItemName: string): LongInt;
function GetLocalIPAddress: string;

procedure SwitchConnection(SecurityVar: TSecurityVars; FormHandle: TForm; DComConnection: TDcomConnection); overload;
procedure SwitchConnection(SecurityVar: TSecurityVars; FormHandle: TForm; SocketConnection: TSocketConnection); overload;
procedure AssignADOConnection(SecurityVar: TSecurityVars; FormHandle: TForm; FADOConn: TADOConnection);
procedure ProcessKeys(Sender: TObject; var Key: Word; Shift: TShiftState);

procedure Dial(Phone, Description: string);
procedure CallDialer(PhoneNumber, PhoneLabel: string; PhoneDataSource: TwwDataSource; PhoneDataSet: TwwClientDataSet);
procedure CallDialer_ADO(PhoneNumber, PhoneLabel: string; PhoneDataSource: TwwDataSource; PhoneDataSet: TADODataSet);

function ShowPlans(PlanVars: TPlanVars; fADOConn: TADOConnection): string;
function ConvertStr(Str: string; FPatientKey: Integer): string;
//   procedure MyKeyPress(Sender: TObject; var Key: Char);
procedure Function_Key_Press_ADO(Key: Word; Sender: TObject; Form: TForm; Grid: TwwDBGrid; ACol: Longint; Table: TADODataSet);

  //Added for ONC; by Shyam.
procedure SaveAuditTrailEventLog(ADOConnect: TADOConnection;
  EventID, EventActionCode: string; EventDateTime: TDateTime;
  EventOutcomeIndicator, EventObjectTrigger: string;
  SecVars: TSecurityVars; UserIsRequestor: string;
  PatientInfo: TPatientInfo);

procedure SaveAuditTrailEventLog2014(ADOConnect: TADOConnection;
  EventID, EventActionCode: string; EventDateTime: TDateTime;
  EventOutcomeIndicator, EventObjectTrigger: string;
  SecVars: TSecurityVars; UserIsRequestor: string;
  PatientInfo: TPatientInfo;
  TableName : string; TableKey:integer);

function GetNTPServerTime: TDateTime;

function GetAuditEnableDisable(sTableName: string): integer;

//ODoffice changes sarma 05.12.2015
Function GetProductBrandName(fADOConn : TADOConnection) :TProductBrandVars;
//ODoffice changes sarma 05.12.2015

  //Added for ONC; by Shyam.
procedure ForceWriteToApplicationLog(strMessage: WideString); // Naveen
function IsValidObject(Obj: TObject): Boolean; //Ranjan 09 03 2012
function IsValidClass(Cls: TClass): Boolean; //Ranjan 09 03 2012
//function GetGlobalUserDir: string; external 'mdoffice.exe'; //Commented By Ranjan on 09 10 2012

var CodeKey: string;
  AName: string;
  count: Integer; // variable use to check codes that are already open.
  val, PhraseHandle: Integer; // varuable use to check save event on a code.

  ComputerName: string;
  SecurityVar: TSecurityVars;
  PatientInfo: TPatientInfo; //Added PatientInfo for ONC; by Shyam.
  ProductBrandVars : TProductBrandVars;//ODoffice changes - sarma  
  ADOConnection: TADOConnection;
  bDetailedLog: Boolean;
//  strGlobalUserDir:string; //Commented by Ranjan on 09 10 2012

  sProductBrandName: string;
implementation

uses
  Main, Zoom, StrpName, Dialer;

function IsValidObject(Obj: TObject): Boolean; //Ranjan 09 03 2012
begin
  try
    Result := not IsBadReadPtr(Obj, sizeof(Pointer)) and IsValidClass(Obj.ClassType) and not IsBadReadPtr(Obj, Obj.InstanceSize);
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global --> IsValidObject ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function IsValidClass(Cls: TClass): Boolean; //Ranjan 09 03 2012
var
  i: Integer;
begin
  try
    for i := 0 to 99 do begin
      Result := (Cls = TObject); // note that other modules may have a different root TObject!
      if Result then Exit;
      if IsBadReadPtr(Cls, sizeof(Pointer)) then Break;
      if IsBadReadPtr(Pointer(Integer(Cls) + vmtParent), sizeof(Pointer)) then Break;
      Cls := Cls.ClassParent;
    end;
    Result := False;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->IsValidClass ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;


function HasAccessRights(Staffkey, Right: Integer; ShowMessageBox: Boolean): Boolean;
var
  SecurityRightsQuery: TClientDataSet;
  DComConnection: TDComConnection;
  SocketConnection: TSocketConnection;
begin
  try
    Result := False;
    SecurityRightsQuery := TClientDataSet.Create(Application);
    DComConnection := TDComConnection.Create(Application);
    SocketConnection := TSocketConnection.Create(Application);
    with SecurityRightsQuery do
    begin
      if SecurityVar.bDCOMCon then
      begin
        DCOMConnection.Connected := False;
        DComConnection.ServerName := 'RDMCodesAdjustment';
        DComConnection.ServerGuid := '{C2379C3A-410B-4556-BD41-AA7F8FE41F2A}';
        DCOMConnection.ComputerName := SecurityVar.ComputerName;
        RemoteServer := DCOMConnection;

        DCOMConnection.Connected := True;
        DCOMConnection.AppServer.SetOffice(SecurityVar.ClientKey);
        DComConnection.AppServer.ClientIP := GetLocalIPAddress;
      end
      else
      begin

        SocketConnection.Connected := False;
        SocketConnection.ServerName := 'RDMCodesAdjustment';
        SocketConnection.ServerGuid := '{C2379C3A-410B-4556-BD41-AA7F8FE41F2A}';
        SocketConnection.Host := SecurityVar.ComputerName;
        RemoteServer := SocketConnection;

        SocketConnection.Connected := True;
        SocketConnection.AppServer.SetOffice(SecurityVar.ClientKey);

      end;

      ProviderName := 'CodesTempQueryProvider';
      CommandText := 'SELECT * FROM SecurityMember ' +
        'WHERE SecurityRightKey = ' + IntToStr(Right) + ' and ' +
        '      StaffKey = ' + IntToStr(StaffKey);
      Open;
    end;
    if not ((SecurityRightsQuery.EOF) and (SecurityRightsQuery.BOF)) then Result := True
    else
    begin
      SecurityRightsQuery.Close;
      SecurityRightsQuery.CommandText := 'SELECT RightDescription FROM SecurityRight WHERE SecurityRightKey = ' + IntToStr(Right);
      SecurityRightsQuery.Open;
//<!-- added for the hidden screen lockout issue: by ace
//      Messagebox(AppHandle, PChar('You do not have security rights to "' + SecurityRightsQuery.FieldByName('RightDescription').AsString + '".' + #13 +
//        'Please contact your ' + ProductBrandVars.ProductBrandName+' administrator.'), pChar(ProductBrandVars.ProductBrandName+' Security Rights'), MB_OK + MB_ICONSTOP);
//-->
      //    Application.Messagebox(PChar('You do not have security rights to "' + SecurityRightsQuery.FieldByName('RightDescription').AsString + '".' + #13 +
//      'Please contact your MDoffice administrator.'), 'MDoffice Security Rights', MB_OK + MB_ICONSTOP);
    end;
    SecurityRightsQuery.Close;
//SecurityRightsQuery.Free;//Commented by Ranjan on 09 03 2012
    if IsValidObject(SecurityRightsQuery) then FreeAndNil(SecurityRightsQuery); //Ranjan 09 03 2012
    DComConnection.Close;
//DComConnection.Free;//Commented by Ranjan on 09 03 2012
    if IsValidObject(DComConnection) then FreeAndNil(DComConnection); //Ranjan 09 03 2012
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->HasAccessRights ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function HasAccessRights_ADO(Staffkey, Right: Integer; ShowMessageBox: Boolean): Boolean;
var
  SecurityRightsQuery: TADODataSet;

  //Changes done by Rakesh for ONC
  ADOTempQuery: TADODataSet;
  bEmergUser: Boolean;
  iEmergGroupKey: Integer;
  //Changes done by Rakesh for ONC

begin
  try
    Result := False;

  //Changes done by Rakesh for ONC
    bEmergUser := False;
    ADOTempQuery := TADODataSet.Create(Application);
    with ADOTempQuery do
    begin
      Connection := ADOConnection;
      Close;
      CommandText := 'SELECT EMERGLOGGED FROM STAFF WHERE STAFFKEY=' + Inttostr(StaffKey);
      Open;
      if FieldByName('EMERGLOGGED').AsString = 'Y' then
        bEmergUser := True;
    end;
  //Changes done by Rakesh for ONC

    SecurityRightsQuery := TADODataSet.Create(Application);
    SecurityRightsQuery.Connection := ADOConnection;

  //Changes done by Rakesh for ONC
    if bEmergUser then
    begin
      with ADOTempQuery do
      begin
        Close;
        CommandText := 'SELECT SecurityGroupKey FROM EmergencyAccess WHERE STAFFKEY=' + Inttostr(StaffKey);
        Open;
        iEmergGroupKey := FieldbyName('SecurityGroupKey').AsInteger;
      end;
      with SecurityRightsQuery do
      begin
        Connection := ADOConnection;
        CommandText := 'SELECT * FROM SECURITYDETAIL ' +
          'WHERE ISDELETED = 0 AND SECURITYGROUPKEY = ' + IntToStr(iEmergGroupKey) +
          ' AND SECURITYRIGHTKEY=' + Inttostr(Right);
        Open;
      end;
    end
    else
    begin //Changes done by Rakesh for ONC
      with SecurityRightsQuery do
      begin
        CommandText := 'SELECT * FROM SecurityMember ' +
          'WHERE ISDELETED = 0 AND SecurityRightKey = ' + IntToStr(Right) + ' and ' +
          '      StaffKey = ' + IntToStr(StaffKey);
        Open;
      end;
    end;
    if not ((SecurityRightsQuery.EOF) and (SecurityRightsQuery.BOF)) then Result := True
    else
    begin
      SecurityRightsQuery.Close;
      SecurityRightsQuery.CommandText := 'SELECT RightDescription FROM SecurityRight WHERE SecurityRightKey = ' + IntToStr(Right);
      SecurityRightsQuery.Open;
//<!-- added for the hidden screen lockout issue: by ace
//      Messagebox(AppHandle, PChar('You do not have security rights to "' + SecurityRightsQuery.FieldByName('RightDescription').AsString + '".' + #13 +
//        'Please contact your ' + ProductBrandVars.ProductBrandName+' administrator.'), pChar(ProductBrandVars.ProductBrandName+' Security Rights'), MB_OK + MB_ICONSTOP);
//-->
//    Application.Messagebox(PChar('You do not have security rights to "' + SecurityRightsQuery.FieldByName('RightDescription').AsString + '".' + #13 +
//      'Please contact your MDoffice administrator.'), 'MDoffice Security Rights', MB_OK + MB_ICONSTOP);
    end;

    ADOTempQuery.Close; //Changes done by Rakesh for ONC
//ADOTempQuery.Free;          //Changes done by Rakesh for ONC//Commented by Ranjan on 09 03 2012
    if IsValidObject(ADOTempQuery) then FreeAndNil(ADOTempQuery); //Ranjan 09 03 2012

    SecurityRightsQuery.Close;
//SecurityRightsQuery.Free;//Commented by Ranjan on 09 03 2012
    if IsValidObject(SecurityRightsQuery) then FreeAndNil(SecurityRightsQuery); //Ranjan 09 03 2012
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global --> HasAccessRights_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function Confirm(MsgTXT: PChar): Boolean;
var
  y: string;
   {Generic messagebox for confirmation}
begin
  try
    y := Application.Title + Chr(0);
    case Application.MessageBox(MsgTXT, @y, MB_ICONQUESTION + MB_YESNO) of
      IDYES: Confirm := True;
      IDNO: Confirm := False;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global --> Confirm ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure SwitchConnection(SecurityVar: TSecurityVars; FormHandle: TForm; DComConnection: TDComConnection);
var
  nIndex: Integer;
begin
  try
    DCOMConnection.Connected := False;
    DCOMConnection.ComputerName := SecurityVar.ComputerName;

    for nIndex := 0 to FormHandle.ComponentCount - 1 do
    begin
      if (FormHandle.Components[nIndex] is TwwClientDataSet) then
        (FormHandle.Components[nIndex] as TwwClientDataset).RemoteServer := DCOMConnection;
    end;
    DCOMConnection.Connected := True;
    DCOMConnection.AppServer.SetOffice(SecurityVar.ClientKey);
    DComConnection.AppServer.ClientIP := GetLocalIPAddress;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->SwitchConnection ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;


procedure SwitchConnection(SecurityVar: TSecurityVars; FormHandle: TForm; SocketConnection: TSocketConnection);
var
  nIndex: Integer;
begin
  try
    SocketConnection.Connected := False;
    SocketConnection.Host := SecurityVar.ComputerName;

    for nIndex := 0 to FormHandle.ComponentCount - 1 do
    begin
      if (FormHandle.Components[nIndex] is TwwClientDataSet) then
        (FormHandle.Components[nIndex] as TwwClientDataset).RemoteServer := SocketConnection
    end;
    SocketConnection.Connected := True;
    SocketConnection.AppServer.SetOffice(SecurityVar.ClientKey);
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->SwitchConnection ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure AssignADOConnection(SecurityVar: TSecurityVars; FormHandle: TForm; FADOConn: TADOConnection);
var
  nIndex: Integer;
begin
  try
    for nIndex := 0 to FormHandle.ComponentCount - 1 do
    begin
      if (FormHandle.Components[nIndex] is TADODataSet) then
        (FormHandle.Components[nIndex] as TADODataSet).Connection := FADOConn
      else
        if (FormHandle.Components[nIndex] is TADOQuery) then
          (FormHandle.Components[nIndex] as TADOQuery).Connection := FADOConn
        else
          if (FormHandle.Components[nIndex] is TADOTable) then
            (FormHandle.Components[nIndex] as TADOTable).Connection := FADOConn
          else
            if (FormHandle.Components[nIndex] is TBetterADODataSet) then
              (FormHandle.Components[nIndex] as TBetterADODataSet).Connection := FADOConn
            else
              if (FormHandle.Components[nIndex] is TAdocommand) then //Sarma
                (FormHandle.Components[nIndex] as TAdocommand).Connection := FADOConn
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->AssignADOConnection ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ConfirmSave(MsgTXT: PChar; Table: TObject; DataSource: TObject): Boolean;
{Generic messagebox for save confirmation}
{MsgTXT:     The string you want to be displayed in message box
Table:      The table component where set to be saved is located
DataSource: The DataSource Component attached to the Table}
var
  y: string;

begin
  try
    Result := False;
    if not (Table is TwwClientDataset) or not (DataSource is TwwDataSource) then exit;
    y := Application.Title + Chr(0);
    if TwwDataSource(DataSource).State in [dsEdit, dsInsert] then
    begin
      //    case Application.MessageBox(MsgTXT, @y, MB_ICONQUESTION + MB_YESNOCANCEL) of
      case Application.MessageBox(MsgTXT, PChar(Application.Title), MB_IconQuestion + MB_YESNOCANCEL) of
        IDYES:
          begin
            TwwClientDataset(Table).Post; {Save changes}
            TwwClientDataset(Table).ApplyUpdates(-1);
            Result := True;
          end;
        IDNO:
          begin
            case TwwDataSource(DataSource).State of
              dsEdit: TwwClientDataset(Table).Cancel;
              dsInsert: TwwClientDataset(Table).Delete;
            end;
            Result := True;
          end;
        IDCANCEL: Result := false; {Do nothing}
      end;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmSave ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ConfirmSave_ADO(MsgTXT: PChar; Table: TObject; DataSource: TObject): Boolean;
{Generic messagebox for save confirmation}
{MsgTXT:     The string you want to be displayed in message box
Table:      The table component where set to be saved is located
DataSource: The DataSource Component attached to the Table}
var
  y: string;

begin
  try
    Result := False;
    if not (Table is TADODataSet) or not (DataSource is TwwDataSource) then exit;
    y := Application.Title + Chr(0);
    if TwwDataSource(DataSource).State in [dsEdit, dsInsert] then
    begin
      //    case Application.MessageBox(MsgTXT, @y, MB_ICONQUESTION + MB_YESNOCANCEL) of
      case Application.MessageBox(MsgTXT, PChar(Application.Title), MB_IconQuestion + MB_YESNOCANCEL) of
        IDYES:
          begin
            TADODataSet(Table).Post; {Save changes}
            Result := True;
          end;
        IDNO:
          begin
            case TwwDataSource(DataSource).State of
              dsEdit: TADODataSet(Table).Cancel;
              dsInsert: TADODataSet(Table).Delete;
            end;
            Result := True;
          end;
        IDCANCEL: Result := false; {Do nothing}
      end;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmSave_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ConfirmCancel(MsgTXT: PChar; MsgTitle: string; Table: TObject; DataSource: TObject): Boolean;
var
  y: string;
begin
  try
    Result := False;
    if not (Table is TwwClientDataset) or not (DataSource is TwwDataSource) then exit;
    y := Application.Title + Chr(0);

    if TwwDataSource(DataSource).State in [dsEdit, dsInsert] then
    begin
      case Application.MessageBox(MsgTXT, PChar(MsgTitle), MB_IconQuestion + MB_YESNO) of
        IDYES:
          begin
            case TwwDataSource(DataSource).State of
              dsEdit: TwwClientDataset(Table).Cancel;
              dsInsert: TwwClientDataset(Table).Delete;
            end;
            Result := True;
          end;
        IDNO:
          begin
            Result := False;
          end;
      end;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmCancel ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ConfirmCancel_ADO(MsgTXT: PChar; MsgTitle: string; Table: TObject; DataSource: TObject): Boolean;
var
  y: string;
begin
  try
    Result := False;
    if not (Table is TADODataset) or not (DataSource is TwwDataSource) then exit;
    y := Application.Title + Chr(0);

    if TwwDataSource(DataSource).State in [dsEdit, dsInsert] then
    begin
      case Application.MessageBox(MsgTXT, PChar(MsgTitle), MB_IconQuestion + MB_YESNO) of
        IDYES:
          begin
            case TwwDataSource(DataSource).State of
              dsEdit: TADODataset(Table).Cancel;
              dsInsert: TADODataset(Table).Delete;
            end;
            Result := True;
          end;
        IDNO:
          begin
            Result := False;
          end;
      end;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmCancel_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;
function ConfirmCancel_BetterADO(MsgTXT: PChar; MsgTitle: string; Table: TObject; DataSource: TObject): Boolean;
var
  y: string;
begin
  try
    Result := False;

    if not (Table is TBetterADODataset) or not (DataSource is TDataSource) then exit;
    y := Application.Title + Chr(0);

    if TDataSource(DataSource).State in [dsEdit, dsInsert] then
    begin
      case Application.MessageBox(MsgTXT, PChar(MsgTitle), MB_IconQuestion + MB_YESNO) of
        IDYES:
          begin
            case TDataSource(DataSource).State of
              dsEdit: TBetterADODataset(Table).Cancel;
              dsInsert: TBetterADODataset(Table).Delete;
            end;
            Result := True;
          end;
        IDNO:
          begin
            Result := False;
          end;
      end;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmCancel_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;


function CapAll(MyString: string): string;
{capitalizes all the characters }
var
  I: Integer;
begin
  try
    for I := 1 to Length(MyString) do
      MyString[I] := UpCase(MyString[I]);
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CapAll ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;


function CapFirst(MyString: string): string;
{Capitalizes all first letters in the words in string}
var
  index: Byte;
  First: Boolean;
begin
  try
    Result := MyString;
    First := True;
    for Index := 1 to Length(MyString) do
    begin
      if First then Result[Index] := UpCase(Result[Index]);
      if Result[index] = ' ' then First := True
      else First := False;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CapFirst ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function DisplayZoom(MyString: string): string;
{Displays the zoom form and brings back edited text}
begin
  try
    fZoom := TfZoom.Create(Application);
    fZoom.Memo1.Text := MyString;
    fZoom.ShowModal;
    case fZoom.ModalResult of
      mrOK: MyString := fZoom.Memo1.Text;
      mrCancel: {do nothing MyString is unchanged};
    end;
    Result := MyString;
//fZoom.Free;//Commented by Ranjan on 09 03 2012
    if IsValidObject(fZoom) then FreeAndNil(fZoom); //Ranjan 09 03 2012
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->DisplayZoom ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure Function_Key_Press(Key: Word; Sender: TObject; Form: TForm;
  Grid: TwwDBGrid; ACol: Longint; Table: TwwClientDataset);

begin
  try
    case key of
      {   VK_F1: Application.He0lpCommand(Help_Context, TEdit(Sender).helpContext);}
      //VK_F1: Application.HelpContext(TForm(Sender).HelpContext);//Harry
//      VK_F9: if Table.State in [dsBrowse] then ChangeTableIndex(Grid, KCombo, Table); //Harry  //carl 2003-09-01
      VK_F12: TEdit(Sender).Text := DisplayZoom(TEdit(Sender).Text);
      VK_Up: if (Sender is TwwIncrementalSearch) then Table.Prior; { Scroll up the list }
      VK_Down: if (sender is TwwIncrementalSearch) then Table.Next; { Scroll Down the list }
      VK_Escape: Form.Close; { close the form }
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->Function_Key_Press ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure Function_Key_Press_ADO(Key: Word; Sender: TObject; Form: TForm;
  Grid: TwwDBGrid; ACol: Longint; Table: TADODataSet);
begin
  try
    case key of
      VK_F12: TEdit(Sender).Text := DisplayZoom(TEdit(Sender).Text);
      VK_Up: if (Sender is TwwIncrementalSearch) then Table.Prior; { Scroll up the list }
      VK_Down: if (sender is TwwIncrementalSearch) then Table.Next; { Scroll Down the list }
      VK_Escape: Form.Close; { close the form }
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->Function_Key_Press_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function UpCaseFirstStr(S: string): string;
// capitalizes first letter of every word
var
  index: Byte;
  First: Boolean;
begin
  try
    Result := S;
    First := True;
    for Index := 1 to Length(S) do
    begin
      if First then Result[Index] := UpCase(Result[Index]);
      if Result[index] = ' ' then First := True
      else First := False;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->UpCaseFirstStr ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function CapFirstLetter(S: string): string;
// capitalizes first letter of every word
var
  index: Byte;
  First: Boolean;
begin
  try
    Result := S;
    First := True;
    for Index := 1 to Length(S) do
    begin
      if First then Result[Index] := UpCase(Result[Index]);
      if Result[index] = ' ' then First := False
      else First := False;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CapFirstLetter ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function StripLastName(Name: ShortString): string;
var
  S: string;
begin
  try
    repeat
      Name := StripFrontChars(Name, #32);
      S := RemoveUpTo(Name, ',');
      if S <> '' then
      begin
        StripLastName := S;
        Name := StripFrontChars(Name, #32);
        Name := StripFrontChars(Name, ',');
        S := RemoveFirstWord(Name);
        if S <> '' then
        begin
          Name := StripFrontChars(Name, #32);
          S := RemoveFirstWord(Name);
        end;
      end
      else StripLastName := Name;
    until S = '';
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->StripLastName ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function StripFirstName(Name: ShortString): string;
var
  S: string;
begin
  try
    repeat
      Name := StripFrontChars(Name, #32);
      S := RemoveUpTo(Name, ',');
      if S <> '' then
      begin
        Name := StripFrontChars(Name, #32);
        Name := StripFrontChars(Name, ',');
        S := RemoveFirstWord(Name);
        if S = '' then StripFirstName := Name
        else
        begin
          StripFirstName := S;
          Name := StripFrontChars(Name, #32);
          S := RemoveFirstWord(Name);
        end
      end
      else StripFirstName := Name;
    until S = ''; { end of Repeat (loop)}
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->StripFirstName ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function StripMI(Name: ShortString): string;
var
  S: string;
begin
  try
    repeat
      Name := StripFrontChars(Name, #32);
      S := RemoveUpTo(Name, ',');
      if S <> '' then
      begin
        Name := StripFrontChars(Name, #32);
        Name := StripFrontChars(Name, ',');
        S := RemoveFirstWord(Name);
        if S <> '' then
        begin
          Name := StripFrontChars(Name, #32);
          S := RemoveFirstWord(Name);
          if Name <> '' then StripMI := Name;
        end
        else StripMI := '';
      end
      else StripMI := Name;
    until S = ''; { end of Repeat (loop)}
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->StripMI ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function StripName(Name: ShortString; var LastName, FirstName, MI: string): string;
var
  S: string;
begin
  try
    repeat
      Name := StripFrontChars(Name, #32);
      S := RemoveUpTo(Name, ',');
      if S <> '' then
      begin
        LastName := S;
        Name := StripFrontChars(Name, #32);
        Name := StripFrontChars(Name, ',');
        S := RemoveFirstWord(Name);
        if S = {<>} '' then
        begin
          FirstName := Name;
        end
        else
        begin
          FirstName := S;
          Name := StripFrontChars(Name, #32);
          S := RemoveFirstWord(Name);
          if Name <> '' then MI := Name;
        end;
      end
      else
      begin
        LastName := Name;
      end;
    until S = ''; { end of Repeat (loop)}
    StripName := LastName + ', ' + FirstName + ' ' + MI;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->StripName ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function StripStr(S: string): string; //anil
// strips all balnks
var
  Index: Byte;
begin
  try
    Result := ' ';
    for Index := 1 to Length(S) do
      if S[Index] <> ' ' then Result := Result + S[Index];
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->StripStr ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure EnterField(Sender: TObject; Color: TColor);
begin
  try
    if Sender is TwwDBLookupCombo then
    begin
///      if (TwwDBLookupCombo(Sender).Name = 'wwDBLookupCombo13') then
      ///if (TwwDBLookupCombo(Sender).Tag = 2001) then   // for staffkey
      ///begin
      TwwDBLookupCombo(Sender).ShowButton := True;
      ///  TwwDBLookupCombo(Sender).ReadOnly:= True;
      (Sender as TwwDBLookUpCombo).Color := Color;
      ///  Exit;
     /// end;
     /// if Not (TwwDBLookupCombo(Sender).Name = 'wwDBLookupCombo5') then
     ///   TwwDBLookupCombo(Sender).ShowButton := True;
    end;

    if Sender is TfcColorCombo then
    begin
      TfcColorCombo(Sender).ShowButton := True;
    end;

    if Sender is TwwDBComboBox then
    begin
      TwwDBComboBox(Sender).ShowButton := True;
    end;

    if Sender is TMDoDBLookupCombo then
    begin
      TMDoDBLookupCombo(Sender).ShowButton := True;
    end;

    if Sender is TwwDBComboDlg then
    begin
      TwwDBComboDlg(Sender).ShowButton := True;
      TwwDBComboDlg(Sender).SelStart := 0;
    end;

(*   if Sender is TwwDBLookupCombo then
   begin
///      if (TwwDBLookupCombo(Sender).Name = 'wwDBLookupCombo13') then
      if (TwwDBLookupCombo(Sender).Tag = 2001) then   // for staffkey
      begin
        TwwDBLookupCombo(Sender).ShowButton:= False;
        TwwDBLookupCombo(Sender).ReadOnly:= True;
        (Sender as TwwDBLookUpCombo).Color := Color;
        Exit;
      end;
      if Not (TwwDBLookupCombo(Sender).Name = 'wwDBLookupCombo5') then
        TwwDBLookupCombo(Sender).ShowButton := True;
   end;
*)

    if Sender is TwwDBDateTimePicker then
    begin
      TwwDBDateTimePicker(Sender).ShowButton := True;
      TwwDBDateTimePicker(Sender).SelStart := 0;
    end;

    if Sender is TEdit then
      (Sender as TEdit).Color := Color
    else
      if Sender is TwwIncrementalSearch then
        (Sender as TwwIncrementalSearch).Color := Color
      else
        if Sender is TDBEdit then
          (Sender as TDBEdit).Color := Color
        else
          if Sender is TwwDBEdit then
            (Sender as TwwDBEdit).Color := Color
          else
            if Sender is TwwDBComboDlg then
              (Sender as TwwDBComboDlg).Color := Color
            else
              if Sender is TwwDBLookupCombo then
                (Sender as TwwDBLookUpCombo).Color := Color
              else
                if Sender is TMDoDBLookupCombo then
                  (Sender as TMDoDBLookUpCombo).Color := Color
                else
                  if Sender is TwwDBLookupComboDlg then
                    (Sender as TwwDBLookUpComboDlg).Color := Color
                  else
                    if Sender is TwwKeyCombo then
                      (Sender as TwwKeyCombo).Color := Color
                    else
                      if Sender is TwwDBComboBox then
                        (Sender as TwwDBComboBox).Color := Color
                      else
                        if Sender is TwwDBDateTimePicker then
                          (Sender as TwwDBDateTimePicker).Color := Color;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->EnterField ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure ExitField(Sender: TObject; Color: TColor);
begin
  try
    if Sender is TfcColorCombo then
    begin
      TfcColorCombo(Sender).ShowButton := False;
    end;

    if Sender is TwwDBComboBox then
    begin
      TwwDBComboBox(Sender).ShowButton := False;
    end;

    if Sender is TMDoDBLookupCombo then
    begin
      TMDoDBLookupCombo(Sender).ShowButton := False;
    end;

    if Sender is TwwDBComboDlg then
    begin
      TwwDBComboDlg(Sender).ShowButton := False;
      TwwDBComboDlg(Sender).SelStart := 0;
    end;

    if Sender is TwwDBLookupCombo then
    begin
      ///if Not (TwwDBLookupCombo(Sender).Name = 'wwDBLookupCombo5') then
      TwwDBLookupCombo(Sender).ShowButton := False;
    end;

    if Sender is TwwDBDateTimePicker then
    begin
      TwwDBDateTimePicker(Sender).ShowButton := False;
      TwwDBDateTimePicker(Sender).SelStart := 0;
    end;

   {below is a replacement for udkeys... it will highlight(using color) the object that has focus}
    if Sender is TEdit then
      (Sender as TEdit).Color := Color
    else
      if Sender is TwwIncrementalSearch then
        (Sender as TwwIncrementalSearch).Color := Color
      else
        if Sender is TDBEdit then
          (Sender as TDBEdit).Color := Color
        else
          if Sender is TwwDBEdit then
            (Sender as TwwDBEdit).Color := Color
          else
            if Sender is TwwDBComboDlg then
              (Sender as TwwDBComboDlg).Color := Color
            else
              if Sender is TMDoDBLookupCombo then
                (Sender as TMDoDBLookUpCombo).Color := Color
              else
                if Sender is TwwDBLookupCombo then
                  (Sender as TwwDBLookUpCombo).Color := Color
                else
                  if Sender is TwwDBLookupComboDlg then
                    (Sender as TwwDBLookUpComboDlg).Color := Color
                  else
                    if Sender is TwwKeyCombo then
                      (Sender as TwwKeyCombo).Color := Color
                    else
                      if Sender is TwwDBComboBox then
                        (Sender as TwwDBComboBox).Color := Color
                      else
                        if Sender is TwwDBDateTimePicker then
                          (Sender as TwwDBDateTimePicker).Color := Color;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ExitField ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121

end;

procedure ChangeTableIndex(Sender: TObject; KCombo: TwwKeyCombo; Table: TwwClientDataset);
var
  i: integer;
begin
  try
    with KCombo do
    begin
      if ItemIndex = Items.Count - 1 then // test for last index, if it is then...
        ItemIndex := 0 // set index to first
      else ItemIndex := ItemIndex + 1; // otherwise set next index to +1

//         Table.IndexFieldName := Items[ItemIndex];    // set to table's current index
    end; // with
    MoveTableColumn(Sender, KCombo.Items[KCombo.ItemIndex], 0); // Move the Indexed column to the first column
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ChangeTableIndex ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

// Anil: Moves column selected by 'FieldName' to position 'Order' in TDBGrid or TwwDBGrid

procedure MoveTableColumn(Sender: TObject; FieldName: string; Order: integer);
var
  i: integer;
begin
  try
    if Sender is TwwDBGrid then
    begin
      for i := 0 to (TwwDBGrid(Sender).FieldCount - 1) do
      begin
        if TwwDBGrid(Sender).Fields[i].DisplayLabel = FieldName then
        begin
          TwwDBGrid(Sender).Fields[i].Index := Order;
          Exit;
        end;
      end;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->MoveTableColumn ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure MoveGridColumn(Sender: TObject; FieldName: string; Order: integer);
var
  i: integer;
begin
  try
    if Sender is TwwDBGrid then
    begin
      for i := 0 to (TwwDBGrid(Sender).FieldCount - 1) do
      begin
        if TwwDBGrid(Sender).Fields[i].DisplayLabel = FieldName then
        begin
          TwwDBGrid(Sender).Fields[i].Index := Order;
          Exit;
        end;
      end;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->MoveGridColumn ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ConfirmAndPost(LocalTable, MainTable: TwwClientDataset; sKey, mKey: string): Boolean;
begin
  try
    if LocalTable.State = dsInactive then LocalTable.Active := True;
    if sKey <> '' then
    begin
      if LocalTable.FindKey([sKey]) then
      begin
        if LocalTable.FieldByName(mKey).AsInteger = MainTable.FieldByName(mKey).AsInteger then
        begin
          LocalTable.Close;
          MainTable.Post;
          MainTable.ApplyUpdates(-1);
          Result := True;
        end
        else
        begin
          LocalTable.Close;
          MessageDlg('You cannot use "' + sKey + '" as shotcut, it is already in use' +
            ' for another record.' + Chr(0), mtError, [mbOk], 0);
          Result := False;
        end; // else local table mkey
      end // if local table skey
      else
      begin
        MainTable.Post;
        MainTable.ApplyUpdates(-1);
        Result := True;
      end; //else
    end
    else Result := True;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmAndPost ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end; // function

function IsSameKey(wwMainTbl, wwTable: TwwClientDataset; short, keyname: string): Boolean;
begin
  try
    wwTable.Open;
    if wwMainTbl.State in [dsInsert] then
      if wwTable.Locate(keyname, short, [loCaseInsensitive]) then
      begin
        (*if wwTable.FieldByName(keyname).AsInteger = wwMainTbl.FieldByName(keyname).AsInteger then
        begin
           wwMainTbl.Post;
           wwMainTbl.ApplyUpdates(-1);
           Result := True;
        end
        else  Result := False;  //same shortcut for different key
        end
        *)
        Result := False;
      end
      else
      begin
        wwMainTbl.Post; //no same shortcut, is ok
        try
          wwMainTbl.ApplyUpdates(-1);
        finally
          wwMainTbl.Refresh;
        end;
        Result := True;
      end
    else
    begin
      wwMainTbl.Post; //no same shortcut, is ok
      try
        wwMainTbl.ApplyUpdates(-1);
      finally
        wwMainTbl.Refresh;
      end;
      Result := True;
    end;
    wwTable.Close;
    Screen.Cursor := crDefault;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->IsSameKey ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function IsSameKey_ADO(wwMainTbl, wwTable: TADODataset; short, keyname: string): Boolean;
begin
  try
    wwTable.Open;
    if wwMainTbl.State in [dsInsert] then
      if wwTable.Locate(keyname, short, [loCaseInsensitive]) then
      begin
        Result := False;
      end
      else
      begin
        wwMainTbl.Post; //no same shortcut, is ok
        Result := True;
      end
    else
    begin
      wwMainTbl.Post; //no same shortcut, is ok
      Result := True;
    end;
    wwTable.Close;
    Screen.Cursor := crDefault;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->IsSameKey_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function IsShortValid(wwMainTbl, wwTable: TwwClientDataset; short, keyname: string): Boolean;
begin
  try
    wwTable.Open;
    if wwTable.FindKey([short]) then
    begin
      if wwTable.FieldByName(keyname).AsInteger = wwMainTbl.FieldByName(keyname).AsInteger then
      begin
        Result := True;
      end else
        Result := False; //same shortcut for different key
    end
    else
    begin
      if short = '0' then Result := False
      else Result := True; //no same shortcut, is ok
    end;
    wwTable.Close;
    Screen.Cursor := crDefault;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->IsShortValid ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function IsShortValid_ADO(wwMainTbl, wwTable: TADODataset; short, keyname: string): Boolean;
begin
  try
    wwTable.Open;
    if wwTable.Locate(keyname, short, []) then
    begin
      if wwTable.FieldByName(keyname).AsInteger = wwMainTbl.FieldByName(keyname).AsInteger then
      begin
        Result := True;
      end else
        Result := False; //same shortcut for different key
    end
    else
    begin
      if short = '0' then Result := False
      else Result := True; //no same shortcut, is ok
    end;
    wwTable.Close;
    Screen.Cursor := crDefault;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->IsShortValid_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

// Created by CES Bordie

function CapFirstMemoLetter(MyMemoList: TStrings): string;
var
  x, y, z, Spaces: integer;
  s1, s2, s3: string;
  Mylist: TStrings;
begin
  try
    Mylist := MyMemoList;
    x := 1;
    Spaces := 0;
    for y := 0 to Mylist.count - 1 do
      if Trim(Mylist[y]) <> '' then
      begin
        break;
      end;
    for x := 1 to length(Mylist[y]) do
      if copy(Mylist[y], x, 1) <> ' ' then
      begin
        s1 := UpperCase(Copy(Mylist[y], x, 1)) + Copy(Mylist[y], x + 1, length(Mylist[y]));
        Mylist.delete(y);
        break;
      end
      else
        Spaces := Spaces + 1;
    if spaces > 0 then
    begin
      for z := 1 to spaces do
        s2 := s2 + ' ';
      s3 := s2 + s1;
      Mylist.insert(y, s3);
    end
    else
    begin
      s3 := s1;
      Mylist.insert(y, s3);
    end;
    Result := Mylist.Text;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CapFirstMemoLetter ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

      // Created by CES Bordie

procedure CodesRequiredMsg(CodeMsg: string); // CES bordie
var
  MyMessage, CodeName: string;
begin
  try
    if (CodeMsg = 'The Last Name') or (CodeMsg = 'Guarantor') then
      MyMessage := 'The Guarantor''s first and last name is required!'
    else
      MyMessage := CodeMsg + ' can not be blank!';
    Application.MessageBox(Pchar(MyMessage), 'Guarantor', MB_ICONEXCLAMATION + MB_OK);
    Screen.Cursor := crDefault;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CodesRequiredMsg ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

// Created by CES Bordie

function CodesConfirmSaveMsg(ConfirmFormMsg: string): Integer;
var
  TempComfirmFormMsg: string;
  TempFormTitleMsg: string;
begin
  try
    TempComfirmFormMsg := 'You have made changes in this ' + Copy(ConfirmFormMsg, 1, Length(ConfirmFormMsg) - 5) + '. Do you want to save them?';
    TempFormTitleMsg := ConfirmFormMsg + ': Save';
    Result := Application.MessageBox(Pchar(TempComfirmFormMsg), PChar(TempFormTitleMsg), MB_ICONQUESTION + MB_YESNOCANCEL)
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CodesConfirmSaveMsg ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure DeleteItems(TableToDelete: TTable; ByField: TField);
begin
  try
    TableToDelete.DisableControls; // for faster table traversal
    try
      TableToDelete.First;
      while not TableToDelete.EOF do if ByField.Value = 0 then TableToDelete.Delete;
    finally
      TableToDelete.EnableControls; // always re-enable controls after disabling
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->DeleteItems ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;


function ConfirmToAddCode: Boolean;
begin
  try
    case Application.MessageBox('This Code has no records. Do you want to add a new Code now?', pChar(ProductBrandVars.ProductBrandName), MB_ICONEXCLAMATION + MB_YESNO) of
      IDYES: ConfirmToAddCode := True;
      IDNO: ConfirmToAddCode := False;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmToAddCode ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;


function ConfirmToDelete: Boolean;
begin
  try
    case Application.MessageBox('Are you sure you want to delete this Code', pChar(ProductBrandVars.ProductBrandName), MB_ICONEXCLAMATION + MB_YESNO) of
      IDYES: ConfirmToDelete := True;
      IDNO: ConfirmToDelete := False;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConfirmToDelete ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetKeyValue(DCOMConnection: TDCOMConnection; TempQueryProvName: string; TableName: string; VField: string): Integer; //harvey 12/29/97
var MyQuery: TwwClientDataSet;
begin
  try
    MyQuery := TwwClientDataSet.Create(Application);
    with MyQuery do begin
      RemoteServer := DCOMConnection;
      ProviderName := TempQueryProvName;
      Close;
      CommandText := 'Select Max(' + VField + ') as MaxID from ' + TableName;
      Open;
      if FieldByName('MaxID').AsString <> '' then
        Result := FieldByName('MaxID').AsInteger + 1
      else
        Result := 1;
      Close;
    end;
//MyQuery.Free;//Commented by Ranjan on 09 03 2012
    if IsValidObject(MyQuery) then FreeAndNil(MyQuery); //Ranjan 09 03 2012
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetKeyValue ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetKeyValue_ADO(FADOConn: TADOConnection; TableName: string; VField: string): Integer;
var
  MyQuery: TADODataSet;
begin
  try
    MyQuery := TADODataSet.Create(nil);
    with MyQuery do begin
      Connection := FADOConn;
      CommandText := 'Select Max(' + VField + ') as MaxID from ' + TableName;
      Open;
      if FieldByName('MaxID').AsString <> '' then
        Result := FieldByName('MaxID').AsInteger + 1
      else
        Result := 1;
      Close;
    end;
//MyQuery.Free;//Commented by Ranjan on 09 03 2012
    if IsValidObject(MyQuery) then FreeAndNil(MyQuery); //Ranjan 09 03 2012
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetKeyValue_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetKeyValue(SocketConnection: TSocketConnection; TempQueryProvName: string; TableName: string; VField: string): Integer; //harvey 12/29/97
var MyQuery: TwwClientDataSet;
begin
  try
    MyQuery := TwwClientDataSet.Create(Application);
    with MyQuery do begin
      RemoteServer := SocketConnection;
      ProviderName := TempQueryProvName;
      Close;
      CommandText := 'Select Max(' + VField + ') as MaxID from ' + TableName;
      Open;
      if FieldByName('MaxID').AsString <> '' then
        Result := FieldByName('MaxID').AsInteger + 1
      else
        Result := 1;
      Close;
    end;
//MyQuery.Free;//Commented by Ranjan on 09 03 2012
    if IsValidObject(MyQuery) then FreeAndNil(MyQuery); //Ranjan 09 03 2012
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetKeyValue ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;


function GetKey(DCOMConnection: TDCOMConnection; NumberTableProvName, TempQueryProvName: string; TableName, ItemName: string): LongInt;
var TableNumbers: TwwClientDataSet;
  TempKey: LongInt;
begin
  try
    TableNumbers := TwwClientDataSet.Create(Application);
    with TableNumbers do begin
      RemoteServer := DComConnection;
      ProviderName := NumberTableProvName;
//       TableName := 'Dbo.Numbers';
      IndexFieldNames := 'Item';
      Close;
      Open;
      if not FindKey([ItemName]) then begin
        Insert;
        FieldByName('Item').asString := ItemName;
        FieldByName('LASTNUMBERUSED').asInteger := GetKeyValue(DCOMConnection, TempQueryProvName, TableName, ItemName);
        Post;
      end
      else begin
        Edit;
        TempKey := GetKeyValue(DCOMConnection, TempQueryProvName, TableName, ItemName);
        if (FieldByName('LASTNUMBERUSED').AsInteger + 1) < TempKey then
          FieldByName('LASTNUMBERUSED').AsInteger := TempKey
        else FieldByName('LASTNUMBERUSED').AsInteger := FieldByName('LASTNUMBERUSED').AsInteger + 1;
        Post;
      end;
      ApplyUpdates(2);
      result := TableNumbers.FieldByName('LASTNUMBERUSED').AsInteger;
      Close;
      Free;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetKey ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetKey(SocketConnection: TSocketConnection; NumberTableProvName, TempQueryProvName: string; TableName, ItemName: string): LongInt;
var TableNumbers: TwwClientDataSet;
  TempKey: LongInt;
begin
  try
    TableNumbers := TwwClientDataSet.Create(Application);
    with TableNumbers do begin
      RemoteServer := SocketConnection;
      ProviderName := NumberTableProvName;
//       TableName := 'Dbo.Numbers';
      IndexFieldNames := 'Item';
      Close;
      Open;
      if not FindKey([ItemName]) then begin
        Insert;
        FieldByName('Item').asString := ItemName;
        FieldByName('LASTNUMBERUSED').asInteger := GetKeyValue(SocketConnection, TempQueryProvName, TableName, ItemName);
        Post;
      end
      else begin
        Edit;
        TempKey := GetKeyValue(SocketConnection, TempQueryProvName, TableName, ItemName);
        if (FieldByName('LASTNUMBERUSED').AsInteger + 1) < TempKey then
          FieldByName('LASTNUMBERUSED').AsInteger := TempKey
        else FieldByName('LASTNUMBERUSED').AsInteger := FieldByName('LASTNUMBERUSED').AsInteger + 1;
        Post;
      end;
      ApplyUpdates(-1);
      result := TableNumbers.FieldByName('LASTNUMBERUSED').AsInteger;
      Close;
      Free;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetKey ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetKey_ADO(FADOConn: TADOConnection; TableName, ItemName: string): LongInt;
var TableNumbers: TADODataSet;
  TempKey: LongInt;
begin
  try
    TableNumbers := TADODataSet.Create(nil);
    with TableNumbers do
    begin
      Connection := ADOConnection;
      CommandText := 'Select * from Numbers';
      Open;

      if not Locate('Item', ItemName, []) then begin
        Insert;
        FieldByName('Item').asString := ItemName;
        FieldByName('LASTNUMBERUSED').asInteger := GetKeyValue_ADO(ADOConnection, TableName, ItemName);
        Post;
      end
      else begin
        Edit;
        TempKey := GetKeyValue_ADO(ADOConnection, TableName, ItemName);
        if (FieldByName('LASTNUMBERUSED').AsInteger + 1) < TempKey then
          FieldByName('LASTNUMBERUSED').AsInteger := TempKey
        else FieldByName('LASTNUMBERUSED').AsInteger := FieldByName('LASTNUMBERUSED').AsInteger + 1;
        Post;
      end;
      result := TableNumbers.FieldByName('LASTNUMBERUSED').AsInteger;
      Close;
      Free;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetKey_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;



(*
Function GetKeyValue(DCOMConnection : TDCOMConnection; TempQueryProvName: String;  TableName : String; VField : String) : Integer;//harvey 12/29/97
var MyQuery : TwwClientDataSet;
begin
   MyQuery:= TwwClientDataSet.Create(Application);
   With MyQuery do begin
     RemoteServer := DCOMConnection;
     ProviderName := TempQueryProvName;
     Close;
     CommandText := 'Select Max(' + VField + ') as MaxID from ' + TableName;
     Open;
     if FieldByName('MaxID').AsString <> '' then
       Result := FieldByName('MaxID').AsInteger + 1
     else
       Result := 1;
     Close;
   end;
//MyQuery.Free;//Commented by Ranjan on 09 03 2012
if IsValidObject(MyQuery) then FreeAndNil(MyQuery); //Ranjan 09 03 2012
End;

function GetKey(DCOMConnection : TDCOMConnection; NumberTableProvName, TempQueryProvName: String;  TableName, ItemName: String):LongInt;
var TableNumbers:TwwClientDataSet;
    TempKey:LongInt;
begin
  TableNumbers := TwwClientDataSet.Create(Application);
  with TableNumbers do begin
       RemoteServer := DComConnection;
       ProviderName := NumberTableProvName;
       IndexFieldNames := 'Item';
       Close;
       Open;
       if not FindKey([ItemName]) then begin
          Insert;
          FieldByName('Item').asString := ItemName;
          FieldByName('LASTNUMBERUSED').asInteger := GetKeyValue(DCOMConnection, TempQueryProvName, TableName, ItemName);
          Post;
          ApplyUpdates(-1);
       end
       else begin
          Edit;
          TempKey:=GetKeyValue(DCOMConnection, TempQueryProvName, TableName, ItemName);
          if (FieldByName('LASTNUMBERUSED').AsInteger + 1) < TempKey then
             FieldByName('LASTNUMBERUSED').AsInteger:=TempKey
          else FieldByName('LASTNUMBERUSED').AsInteger:=FieldByName('LASTNUMBERUSED').AsInteger + 1;
          Post;
          ApplyUpdates(-1);
       end;
       result := TableNumbers.FieldByName('LASTNUMBERUSED').AsInteger;
       Close;
       Free;
  end;
end;
*)


procedure ProcessKeys(Sender: TObject; var Key: Word; Shift: TShiftState);
{harvey 11-05-1998:  added in replacement for UDKEYS}
var
  MyForm: TCustomForm;
  CtlDir: Word;
begin
  try
    case Key of
      VK_UP, VK_DOWN:
        begin
          if ssAlt in Shift then Exit; //Reserve alt-down for dropdown
          MyForm := GetParentForm(TControl(Sender));
          if Key = VK_UP then CtlDir := 1
          else CtlDir := 0;

         {when user presses up or down key and dropdown list is visible then don't skip to next
         control so user can navigate the list--harv}

          if (Sender is TImagePicker) and TImagePicker(Sender).DroppedDown then exit;
          if (Sender is TwwDBComboBox) and TwwDBComboBox(Sender).DroppedDown then exit;
          if (Sender is TwwDBLookupCombo) and TwwDBLookupCombo(Sender).Grid.Visible then exit;
          if (Sender is TMDoDBLookupCombo) and TMDoDBLookupCombo(Sender).Grid.Visible then exit;
          if (Sender is TwwKeyCombo) and TwwKeyCombo(Sender).DroppedDown then exit;
          if (Sender is TfcColorCombo) and TfcColorCombo(Sender).DroppedDown then exit;

          if not (MyForm = nil) then SendMessage(MyForm.Handle, WM_NEXTDLGCTL, CtlDir, 0);

          Key := 0;
        end;
      VK_RETURN:
        begin
          MyForm := GetParentForm(TControl(Sender));
          if ssShift in Shift then CtlDir := 1
          else CtlDir := 0;

         {when user hits enter and dropdown list is visible then don't skip to next control but
         have focus on the current control--harv}

          if (Sender is TImagePicker) and TImagePicker(Sender).DroppedDown then exit;
          if (Sender is TwwDBComboBox) and TwwDBComboBox(Sender).DroppedDown then exit;
          if (Sender is TwwDBLookupCombo) and TwwDBLookupCombo(Sender).Grid.Visible then exit;
          if (Sender is TMDoDBLookupCombo) and TMDoDBLookupCombo(Sender).Grid.Visible then exit;
          if (Sender is TwwKeyCombo) and TwwKeyCombo(Sender).DroppedDown then exit;
          if (Sender is TfcColorCombo) and TfcColorCombo(Sender).DroppedDown then exit;

          if not (MyForm = nil) then SendMessage(MyForm.Handle, WM_NEXTDLGCTL, CtlDir, 0);

          Key := 0;
        end;
    end;
    application.processmessages;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ProcessKeys ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetLocalIPAddress: string;
type
  TaPInAddr = array[0..10] of PInAddr;
  PaPInAddr = ^TaPInAddr;
var
  phe: PHostEnt;
  pptr: PaPInAddr;
  Buffer: array[0..63] of char;
  I: integer;
  GInitData: TWSADATA;
begin
  try
    WSAStartup($101, GInitData);
    Result := '';
    GetHostName(Buffer, SizeOf(Buffer));
    phe := GetHostByName(Buffer);
    if phe = nil then
      Exit;
    pptr := PaPInAddr(Phe^.h_addr_list);
    I := 0;
    while pptr^[I] <> nil do
    begin
      Result := StrPas(inet_ntoa(pptr^[I]^));
      Inc(I);
    end;
    WSACleanup;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetLocalIPAddress ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure CallDialer(PhoneNumber, PhoneLabel: string; PhoneDataSource: TwwDataSource; PhoneDataSet: TwwClientDataSet);
begin
  try
    Dial(PhoneNumber, PhoneLabel);
    case PhoneDataSource.State of
      dsEdit: PhoneDataSet.Cancel;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CallDialer ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure CallDialer_ADO(PhoneNumber, PhoneLabel: string; PhoneDataSource: TwwDataSource; PhoneDataSet: TADODataSet);
begin
  try
    Dial(PhoneNumber, PhoneLabel);
    case PhoneDataSource.State of
      dsEdit: PhoneDataSet.Cancel;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->CallDialer_ADO ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

procedure Dial(Phone, Description: string);
var DialSystem: TfDialForm;
begin
  try
    try
      DialSystem := TfDialForm.Create(Application);
      DialSystem.Phone := Phone;
      DialSystem.Description := Description;
      DialSystem.ShowModal;
    finally
//DialSystem.Free;//Commented by Ranjan on 09 03 2012
      if IsValidObject(DialSystem) then FreeAndNil(DialSystem); //Ranjan 09 03 2012
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->Dial ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ShowScanlite(nIndex: Integer; LocationKey: Integer): Integer;
const
  ForOfficeLogo = 3;
type
  TShowFunc = function(SecurityVar: TSecurityVars; SourceKey, Index: Integer): Integer;
var
  hLib: THandle;
  ShowFunc: TShowFunc;
  strProc: string;
  PageIndex: Integer;
begin
  try
    hLib := LoadLibrary('MDDocumentslite.dll');
    if hLib < 32 then
    begin
      MessageDlg('MDDocumentslite.dll', mtInformation, [mbOK], 0);
      Exit;
    end;
  (*case nIndex of
    0: begin
         strProc   := 'ShowPatientPhoto';
         PageIndex := 0;
       end;
    1: begin
         strProc   := 'ShowPatientImage';
         PageIndex := 0;
       end;
  end;
  *)
    ShowFunc := TShowFunc(GetProcAddress(hLib, PChar('ShowOfficeLogo')));
    Result := ShowFunc(SecurityVar, LocationKey, ForOfficeLogo); // 3 = for Office Logo
    FreeLibrary(hLib);
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ShowScanlite ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ShowScanlite(Caption, SourceType: string; SourceKey: Integer): Integer;
type
  TShowFunc = function(SecurityVars: TSecurityVars; FormCaption, SourceType: string; SourceKey: Integer): Integer;
var
  hLib: THandle;
  ShowFunc: TShowFunc;
  strProc: string;
  PageIndex: Integer;
begin
  try
    hLib := LoadLibrary('MDDocumentslite.dll');
    if hLib < 32 then
    begin
      MessageDlg('MDDocumentslite.dll', mtInformation, [mbOK], 0);
      Exit;
    end;
    ShowFunc := TShowFunc(GetProcAddress(hLib, 'ShowGenericScanner'));
    Result := ShowFunc(SecurityVar, Caption, SourceType, SourceKey);
    FreeLibrary(hLib);
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ShowScanlite ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetImageType(ImageStream: TMemoryStream): string;
var Filetype: string;
  Fwidth: SmallInt;
  FHeight: SmallInt;
  Fbitspixel: SmallInt;
  Fplanes: SmallInt;
  Fnumcolors: SmallInt;
  Fcompression: string;
begin
  try
    if GetBlobInfo(ImageStream.Memory,
      ImageStream.Size,
      Filetype,
      Fwidth,
      FHeight,
      Fbitspixel,
      Fplanes,
      Fnumcolors,
      Fcompression) then
      result := filetype;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetImageType ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ShowPlans(PlanVars: TPlanVars; fADOConn: TADOConnection): string;
var
  HLib: THandle;
  Handle: THandle;
  FShowPlans: TShowPlans;
begin
  try
    Screen.Cursor := crHourGlass;
    try
      hLib := LoadLibrary('Plans_ADO.DLL');
      if hlib < 32 then begin
        MessageDlg('No Plans_ADO.DLL', mtInformation, [mbOK], 0);
        Exit;
      end;
      FShowPlans := TShowPlans(GetProcAddress(hLib, 'ShowPlansFormADO'));

      PlanVars.MainHandle := Application.Handle;
      Result := FShowPlans(PlanVars, fADOConn);
    finally
      FreeLibrary(hLib);
    end;
    Screen.Cursor := crDefault;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ShowPlans ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetVersionNumber(ModuleName: string): string;
const
  InfoNum = 10;
  InfoStr: array[1..InfoNum] of string =
  ('CompanyName', 'FileDescription', 'FileVersion', 'InternalName', 'LegalCopyright',
    'LegalTradeMarks', 'OriginalFileName', 'ProductName', 'ProductVersion', 'Comments');
var
  n, Len: DWORD;
  Buf: PChar;
  Value: PChar;
begin
  try
    n := GetFileVersionInfoSize(PChar(ModuleName), n);
    if n > 0 then
    begin
      Buf := AllocMem(n);
      GetFileVersionInfo(PChar(ModuleName), 0, n, Buf);
      if VerQueryValue(Buf, PChar('StringFileInfo\040904E4\' + InfoStr[3]), Pointer(Value), Len) then
        Result := Value;
      FreeMem(Buf, n);
    end
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetVersionNumber ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function OpenPhraseFinderForm(PhraseFinderVars: TPhraseFinderVars; fADOConn: TADOConnection): LongInt;
var
  HLib: THandle;
  FShowPhraseFinder: TShowPhraseFinder;
begin
  try
    Result := -1;
    hLib := LoadLibrary('PhraseFinder_ADO.DLL');
    if hlib < 32 then begin
      MessageDlg('No PhraseFinder_ADO.DLL', mtInformation, [mbOK], 0);
      Exit;
    end;
    FShowPhraseFinder := TShowPhraseFinder(GetProcAddress(hLib, 'ShowPhraseFinder'));
    Result := FShowPhraseFinder(PhraseFinderVars, '', fADOConn);
    FreeLibrary(hLib);
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->OpenPhraseFinderForm ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function ConvertStr(Str: string; FPatientKey: Integer): string;
type
  TConvertString = function(Str: string; FPatientKey: Integer): string;
var
  ConvertString: TConvertString;
begin
  try
    if FPatientKey = 0 then exit;
    ConvertString := TConvertString(GetProcAddress(PhraseHandle, 'ConvertString'));
    Result := ConvertString(Str, FPatientKey);
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->ConvertStr ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function AutoCapitalizeFirstLetter(Sender: TObject): string;
var
  LengthCounter: Integer;
  strWholeValue: string;
  strSingleValue: string;
begin
  try
    Result := '';

    strWholeValue := UpperCase(Copy(TwwDBEdit(Sender).Text, 1, 1)) + Copy(TwwDBEdit(Sender).text, 2, length(TwwDBEdit(Sender).text));
    LengthCounter := 1;
    if Length(strWholeValue) <> 0 then
      repeat
        if Copy(strWholeValue, LengthCounter, 1) = ' ' then
        begin
          strSingleValue := UpperCase(Copy(strWholeValue, LengthCounter + 1, 1));
          Delete(strWholeValue, LengthCounter + 1, 1);
          Insert(strSingleValue, strWholeValue, LengthCounter + 1);
        end;

        Inc(LengthCounter);
      until LengthCounter >= length(strWholeValue);

    Result := strWholeValue;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->AutoCapitalizeFirstLetter ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function IsValidDate(MyTest: string): Boolean;
begin
  try
    Result := True;
    try
      StrToDateTime(MyTest);
      if (length(MyTest) = 2) or (length(MyTest) = 1) then
      begin
        if (strtoint(MyTest) >= 1) and (strtoint(MyTest) <= 24) then Result := False;
      end;
    except
      Result := False;
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->IsValidDate ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

//Added for ONC; by Shyam.

procedure SaveAuditTrailEventLog(ADOConnect: TADOConnection;
  EventID, EventActionCode: string; EventDateTime: TDateTime;
  EventOutcomeIndicator, EventObjectTrigger: string;
  SecVars: TSecurityVars; UserIsRequestor: string;
  PatientInfo: TPatientInfo);
var
  AuditADOCmd: TADOCommand;
begin
  try
    try
      AuditADOCmd := TADOCommand.Create(nil);
      AuditADOCmd.Connection := ADOConnect;

      AuditADOCmd.CommandText := ' EXEC SC_UPDATEAUDITTRAILEVENT '
        + QuotedStr(EventID) + ', ' + QuotedStr(EventActionCode) + ', ' + QuotedStr(DateTimeToStr(EventDateTime)) + ', '
        + QuotedStr(DateTimeToStr(Secvars.nStaffSystemLoginTime)) + ', '
        + QuotedStr(EventOutcomeIndicator) + ', ' + QuotedStr(EventObjectTrigger) + ', '
        + QuotedStr(IntToStr(SecVars.nStaffKey)) + ', ' + QuotedStr(SecVars.nStaffName) + ', '
        + QuotedStr(UserIsRequestor) + ', ' + QuotedStr(IntToStr(SecVars.nRoleIDCode)) + ', ' + QuotedStr(SecVars.MachineName) + ', '
        + QuotedStr(IntToStr(PatientInfo.PatientKey)) + ', ' + QuotedStr(PatientInfo.Name) + ', ' + QuotedStr(DateTimeToStr(PatientInfo.BirthDate)) + ', '
        + QuotedStr(PatientInfo.Gender) + ', ' + QuotedStr(PatientInfo.Address) + ', ' + QuotedStr(IntToStr(PatientInfo.Account));

   // AuditADOCmd.Execute;
      try
        AuditADOCmd.Execute;
      except
        on E: Exception do
          ForceWriteToApplicationLog('Error in Global.pas -> SaveAuditTrailEventLog -> ' + E.Message + ' ' + AuditADOCmd.CommandText); // Naveen
      end;

    finally
//AuditADOCmd.Free;//Commented by Ranjan on 09 03 2012
      if IsValidObject(AuditADOCmd) then FreeAndNil(AuditADOCmd); //Ranjan 09 03 2012
    end;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->SaveAuditTrailEventLog ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;

function GetNTPServerTime: TDateTime;
begin
  try
    Result := Now;
  except
    on E: Exception do
    begin
      ForceWriteToApplicationLog('Error log -->CodesDLL --> Global -->GetNTPServerTime ..Error details :  ' + E.Message);
    end;
  end; //PrasadReddy 20121121
end;
//Added for ONC; by Shyam.

procedure ForceWriteToApplicationLog(strMessage: WideString);
var
  strLog: widestring;
  eLog: TextFile;
  strPath: string;
  fConfig: TIniFile;
  sLogFileName: string;
begin
  try
    if Pos('abort', LowerCase(strMessage)) > 0 then //sarma on Mar.12.2013
      Exit;
      
    strPath := ExtractFilePath(Application.Exename);
    strLog := Format('%s'#09'%s',
      [FormatDateTime('mm/dd/yy h:nn:ssa/p', Now), strMessage]);

    AssignFile(eLog, strPath + 'CodesDLLADO.Log');

    if FileExists(strPath + 'CodesDLLADO.Log') then
      Append(eLog)
    else
      ReWrite(eLog);

    Writeln(eLog, strLog);
    CloseFile(eLog);
  except
 //
  end;
end; //PrasadReddy 20121121

procedure SaveAuditTrailEventLog2014(ADOConnect: TADOConnection;
  EventID, EventActionCode: string; EventDateTime: TDateTime;
  EventOutcomeIndicator, EventObjectTrigger: string;
  SecVars: TSecurityVars; UserIsRequestor: string;
  PatientInfo: TPatientInfo;
  TableName : string; TableKey:integer);
var
  AuditADOCmd: TADOCommand;
begin
  try
    AuditADOCmd := TADOCommand.Create(nil);
    AuditADOCmd.Connection := ADOConnect;

    AuditADOCmd.CommandText := ' EXEC SC_UPDATEAUDITTRAILEVENT2014 '
      + QuotedStr(EventID) + ', ' + QuotedStr(EventActionCode) + ', ' + QuotedStr(DateTimeToStr(EventDateTime)) + ', '
      + QuotedStr(DateTimeToStr(Secvars.nStaffSystemLoginTime)) + ', '
      + QuotedStr(EventOutcomeIndicator) + ', ' + QuotedStr(EventObjectTrigger) + ', '
      + QuotedStr(IntToStr(SecVars.nStaffKey)) + ', ' + QuotedStr(SecVars.nStaffName) + ', '
      + QuotedStr(UserIsRequestor) + ', ' + QuotedStr(IntToStr(SecVars.nRoleIDCode)) + ', ' + QuotedStr(SecVars.MachineName) + ', '
      + QuotedStr(IntToStr(PatientInfo.PatientKey)) + ', ' + QuotedStr(PatientInfo.Name) + ', ' + QuotedStr(DateTimeToStr(PatientInfo.BirthDate)) + ', '
      + QuotedStr(PatientInfo.Gender) + ', ' + QuotedStr(PatientInfo.Address) +
      ', ' + QuotedStr(IntToStr(PatientInfo.Account))  + ', '
       + QuotedStr(TableName) + ', ' + QuotedStr(IntToStr(TableKey)) ;
    try
      AuditADOCmd.Execute;
    except
      on E: Exception do
        ForceWriteToApplicationLog('Error in Global.pas -> SaveAuditTrailEventLog2014 -> ' + E.Message + ' ' + AuditADOCmd.CommandText); // Naveen on July 25,2012
    end;

  finally
    FreeAndNil(AuditADOCmd);
  end;
end;

function GetAuditEnableDisable(sTableName: string): integer;
var AuditEnableDisable: TADOQuery;
begin
  AuditEnableDisable := TADOQuery.Create(nil);
  Result := 1;
  if sTableName <> '' then
  begin
    if AuditEnableDisable <> nil then
    begin
      with AuditEnableDisable do
      begin
        Connection := ADOConnection;
        Sql.Text := 'SELECT ISENABLED FROM AUDITTRAILENABLEDISABLE WHERE TABLENAME = ''' + Trim(sTableName)+'''';
        Open;
        if RecordCount > 0 then
          Result := FieldByName('ISENABLED').AsInteger;
        Close;
      end;
    end;
    FreeAndNil(AuditEnableDisable);
  end;
  if AuditEnableDisable <> nil then
    FreeAndNil(AuditEnableDisable);
end;

{
procedure ForceWriteToApplicationLog(strMessage: WideString);
var
  strLog: string;
  eLog: TextFile;
  strPath: string;
begin
  try
  if Not bDetailedLog then //Ranjan 09 04 2012
  exit;
    strPath := ExtractFilePath(Application.Exename); //Commented by Ranjan on 09 03 2012 Uncommented by Ranjan on 09 10 2012
//    strPath := strGlobalUserDir; //Ranjan 09 04 2012 Commented by Ranjan on 09 10 2012

    strLog := Format('%s'#09'%s',
      [FormatDateTime('mm/dd/yy h:nna/p', Now), strMessage]);

    AssignFile(eLog, strPath + 'CodesDLL.Log');

    if FileExists(strPath + 'CodesDLL.Log') then
      Append(eLog)
    else
      ReWrite(eLog);

    Writeln(eLog, strLog);
    CloseFile(eLog);
  except
  end;
end;
}

function Capitalize(Texto:String): String;
begin
  if Texto <> '' then
  begin
    Texto := UpperCase(Copy(Texto,1,1))+LowerCase(Copy(Texto,2, Length(Texto)));
    Result := Texto;
  end;
end;

Function GetProductBrandName(fADOConn : TADOConnection) :TProductBrandVars;
var
  MyDataset : TBetterADODataSet;
begin
  //ODoffice changes sarma 05.12.2015
  try
   Result.ProductBrandKey :=0;
   Result.ProductBrandName :='MDoffice';
    Try
      MyDataset := TBetterADODataSet.Create(Nil);
      with MyDataset do
      begin
        Connection := fADOConn;
        CommandText := 'SELECT ISNULL(PRODUCTBRAND,0) AS PRODUCTBRAND FROM MDOSYSTEM  with (nolock)';
        Open;
        if RecordCount > 0 Then
        begin
           if FieldbyName('PRODUCTBRAND').AsInteger >0 Then
           begin
             Result.ProductBrandKey :=1;
             Result.ProductBrandName :='ODoffice';
           end;
        end;
      end;
    except
    on E: Exception do
       ForceWriteToApplicationLog('Error in Global.pas -> GetProductBrandName -> ' + E.Message );
     end;
  finally
    FreeAndNil(MyDataset);
  end;
end;

end. //main

